<?php
declare (strict_types=1);

namespace app\command;

use Carbon\Carbon;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;
use yunwuxin\cron\Task;

class CurlRequestLogCronRename extends Task
{
    /**
     * 配置指令.
     */
    protected function configure()
    {
        // 分 时 日 月 周
        $this->expression = '0 1 * * *';
//        $this->expression = '* * * * *';
    }

    protected function handle()
    {
        $day = Carbon::now()->subDay()->format('ymd');

        $tableName = 'curl_request_log_' . $day;

        if (Db::execute("SHOW TABLES LIKE '$tableName'")) {
            echo('已存在' . $tableName);
            return;
        }

        // 修改表名
        Db::execute('ALTER TABLE curl_request_log RENAME ' . $tableName);

        $sql = <<<SQL
CREATE TABLE `curl_request_log` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增id',
  `url` text COMMENT '请求地址',
  `request` mediumtext COMMENT '请求数据',
  `response` mediumtext COMMENT '响应数据',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`),
  KEY `time` (`created_at`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='curl get/post 请求日志';
SQL;

        //创建表
        DB::execute($sql);


        //前15天的表，如果存在则删除
        $oldDay = Carbon::now()->subDay(15)->format('ymd');
        $oldTableName = 'curl_request_log_' . $oldDay;
        try {
            DB::execute('DROP TABLE '.$oldTableName.';');
        }catch (\Exception $exception){
        }
        // 指令输出
        echo('修改名称成功');
    }
}
